// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/type/subfield.h>
#include <pollux/type/tokenizer.h>

namespace kumo::pollux::common {
    Subfield::Subfield(
        const std::string &path,
        const std::shared_ptr<Separators> &separators) {
        Tokenizer tokenizer(path, separators);
        POLLUX_CHECK(tokenizer.hasNext(), "Column name is missing: {}", path);

        auto firstElement = tokenizer.next();
        POLLUX_CHECK(
            firstElement->kind() == kNestedField,
            "Subfield path must start with a name: {}",
            path);
        std::vector<std::unique_ptr<PathElement> > pathElements;
        pathElements.push_back(std::move(firstElement));
        while (tokenizer.hasNext()) {
            pathElements.push_back(tokenizer.next());
        }
        path_ = std::move(pathElements);
    }

    Subfield::Subfield(std::vector<std::unique_ptr<Subfield::PathElement> > &&path)
        : path_(std::move(path)) {
        POLLUX_CHECK_GE(path_.size(), 1);
    }

    Subfield Subfield::clone() const {
        Subfield subfield;
        subfield.path_.reserve(path_.size());
        for (auto &element: path_) {
            subfield.path_.push_back(element->clone());
        }
        return subfield;
    }
} // namespace kumo::pollux::common
